#!/usr/bin/env python
# coding: utf-8

import grpc
from rpc import service_pb2_grpc, service_pb2

import time
from threading import Thread
import json

def print_message_list(stub, destination):
    response = stub.fetchMessageList(service_pb2.FetchMessageList(destination=destination))
    msg_list = json.loads(response.message)
    for msg in msg_list:
        msg_key = msg['sender'] + msg['msg']
        if msg_key not in chat_history:
            print(msg['sender'] + ": " + msg['msg'] + '\n')
            chat_history.add(msg_key)
        
        
def subprocess_print():
    while True:
        print_message_list(stub, destination)
        time.sleep(1)


chat_history = set()



if __name__ == '__main__':
    print("Will try to connect server ...")
    channel = grpc.insecure_channel("localhost:1369")
    stub = service_pb2_grpc.WechatServiceStub(channel)

    destination = input("目标聊天:")

    if not destination:
        destination = '靠力气赚钱心里才踏实'

    t1 = Thread(target=subprocess_print)
    t1.start() 

    while True:
        content = input()
        stub.sendMessage(service_pb2.SendMessage(destination=destination, content=content))